package iit.projects.etaxi.view.bean;

import java.util.ArrayList;
import java.util.List;

import javax.faces.event.ActionEvent;

import iit.projects.etaxi.model.entity.Message;
import iit.projects.etaxi.model.service.MessageService;
import iit.projects.etaxi.model.service.ServiceLocator;

public class MessageBackingBean {
	
	private List<Message> messages;
	
	private ServiceLocator serviceLocator;
	private MessageService messageService;
	
	@javax.annotation.PostConstruct
	public void init(){
		messageService = serviceLocator.getMessageService();
		messages = messageService.findAllMessages();
	}
	
	public void selectAll(ActionEvent event){
		for(Message message : messages){
			message.setSelected(true);
		}
	}
	
	public void deselectAll(ActionEvent event){
		for(Message message : messages){
			message.setSelected(false);
		}
	}
	
	public void markAsRead(ActionEvent event){
		List<Message> messages = getSelectedMessages();
		for(Message message : messages){
			message.setRead(true);
		}
		messageService.updateMessages(messages);
	}
	
	public void markAsUnRead(ActionEvent event){
		List<Message> messages = getSelectedMessages();
		for(Message message : messages){
			message.setRead(false);
		}
		messageService.updateMessages(messages);
	}
	
	public void delete(ActionEvent event){
		List<Message> messages = getSelectedMessages();
		messageService.deleteMessages(messages);
		this.messages.removeAll(messages);
	}
	
	public void refresh(ActionEvent event){
		this.messages = messageService.findAllMessages();
	}
	
	private List<Message> getSelectedMessages(){
		
		List<Message> selected = new ArrayList<Message>();
		for(Message message : messages){
			if(message.isSelected()){
				selected.add(message);
			}
		}
		return selected;
	}

	public List<Message> getMessages() {
		return messages;
	}

	public void setMessages(List<Message> messages) {
		this.messages = messages;
	}

	public void setServiceLocator(ServiceLocator serviceLocator) {
		this.serviceLocator = serviceLocator;
	}
}
